<?php
/**
 * Created by PhpStorm.
 * User: xutao
 * Date: 2018/8/6
 * Time: 10:56
 * 广告
 */
namespace app\admin\controller;
use app\common\model\AdModel;

class Ad extends Base{

    //列表
    public function index1(){
  
        $data = AdModel::order('sort desc')->paginate(10);
        $this->assign('data',$data);
        return $this->fetch('ad/index');
    }
    //添加
    public function add(){
        //做多只能有4条广告
            $count = AdModel::count();

        if($count >= 4) return $this->error('广告最多只能为4条');
        if(request()->isPost()){
            //接受参数
            $data = input();
            if(!$data) return $this->error('参数错误');
            $admodel = new AdModel();
            $re = $admodel->allowField(true)->save($data);
            if($re){
                return $this->redirect('/admin/ad/index1');
            }else{
                return $this->error('添加失败');
            }
        }else{
            return $this->fetch();
        }
    }
    //删除
    public function del(){
        if(request()->isAjax()){
            if(!input('id')) return json(['code'=>2,'data'=>'','msg'=>'参数错误']);
            $ee = AdModel::get(input('id'));
            if($ee){
                if(file_exists(ROOT_PATH.$ee['src'])){
                    unlink(ROOT_PATH.$ee['src']);
                }
            }
            $re = AdModel::destroy(input('id'));
            if($re){
                return json(['code'=>200,'data'=>'','msg'=>'删除成功']);
            }else{
                return json(['code'=>1,'data'=>'','msg'=>'删除失败']);
            }
        }else{
            return json(['code'=>0,'data'=>'','msg'=>'非法请求']);
        }
    }
    //编辑
    public function edit(){
        if(request()->isPost()){
            $data = input('post.');
            if(!$data) return $this->error('参数错误');
            $admodel = AdModel::get($data['id']);
            $re = $admodel->allowField(true)->save($data);
            if($re){
                return $this->redirect('/admin/ad/index1');
            }else{
                return $this->error('修改失败');
            }
        }else{
            $id = input('id');
            $data = AdModel::get($id);
            if(!$data) return $this->error('没有找到该广告');
            $this->assign('data',$data);
            return $this->fetch();
            
        }
    }


}